#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import ssl
import pika

class RabbitMQ:

    def __init__(self, host, port, virtual_host, username, password):
        credentials = pika.PlainCredentials(username, password)
        parameters = []

        # 统一处理所有连接参数组合
        if isinstance(host, list) and isinstance(port, list):
            # 当host和port都是列表时，按索引配对
            for h, p in zip(host, port):
                parameters.append(pika.ConnectionParameters(
                    host=h,
                    port=int(p),
                    heartbeat=300,
                    virtual_host=virtual_host,
                    credentials=credentials
                ))
        elif isinstance(host, list):
            # 当只有host是列表时，使用固定端口
            for h in host:
                parameters.append(pika.ConnectionParameters(
                    host=h,
                    port=int(port),
                    heartbeat=300,
                    virtual_host=virtual_host,
                    credentials=credentials
                ))
        elif isinstance(port, list):
            # 当只有port是列表时，使用固定host
            for p in port:
                parameters.append(pika.ConnectionParameters(
                    host=host,
                    port=int(p),
                    heartbeat=300,
                    virtual_host=virtual_host,
                    credentials=credentials
                ))
        else:
            # 单节点连接
            parameters.append(pika.ConnectionParameters(
                host=host,
                port=int(port),
                heartbeat=300,
                virtual_host=virtual_host,
                credentials=credentials
            ))

        # 移除冗余的单节点连接逻辑
        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()

    # 消费
    def consumption(self, queue_name):
        # 定义一个回调函数来处理接收到的消息
        def callback(ch, method, properties, body):
            print(" [x] Received %r" % body)    # 打印接收到的消息
        # 设置通道的回调函数，当有消息到达时会调用这个函数
        self.channel.basic_consume(queue='my_quorum_queue', on_message_callback=callback, auto_ack=True)  # 自动确认消息
        # 开始消费消息
        print(' [*] Waiting for messages. To exit press CTRL+C')
        self.channel.start_consuming()    # 开始循环监听消息    # 确保关闭连接
        self.connection.close()  # 确保关闭连接


if __name__ == "__main__":

    host = "192.168.2.218"
    port = [5672, 5673, 5674]
    username = "admin"
    password = "123456"
    virtual_host = "customize"
    rabbitmq = RabbitMQ(host, port, virtual_host, username, password)
    rabbitmq.consumption("my_quorum_queue")
